package com.aaa.config;

import cn.hutool.json.JSONUtil;
import com.aaa.entity.Result;
import com.aaa.filter.JwtVerifyFilter;
import com.aaa.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/1 21:35
 * @description：
 * @modified By：
 * @version:
 */
@Configuration
public class MySpringSecurityConfig {

    @Autowired
    private JwtVerifyFilter jwtVerifyFilter;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //定义表单规则和过滤器
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.addFilterBefore(jwtVerifyFilter, UsernamePasswordAuthenticationFilter.class);
        //表单规则
        http.formLogin()
                //.loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(successHandler())
                .permitAll();
        //禁用跨域请求
        http.csrf().disable();

        //其他请求必须认证后才能访问
        http.authorizeRequests().anyRequest().authenticated();

        //无权限处理
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

        //设置跨域运行
        http.cors();

        return http.build();
    }


    private AuthenticationSuccessHandler successHandler(){
        return ((request,response,authentication) ->{
            //设置返回值类型
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Map<String,Object> map = new HashMap<>();
            User principal = (User) authentication.getPrincipal();
            String username = principal.getUsername();
            Collection<GrantedAuthority> authorities = principal.getAuthorities();
            List<String> list = authorities.stream().map(item -> item.getAuthority()).collect(Collectors.toList());
            map.put("username",username);
            map.put("authorities",list);
            String token = JwtTool.createJWT(map);
            Result result = new Result(200,"登陆成功",token);
            String jsonStr = JSONUtil.toJsonStr(result);
            writer.println(jsonStr);
            writer.flush();
            writer.close();
        });
    }

    private AccessDeniedHandler accessDeniedHandler(){
        return((request,response,Authentication) ->{
            response.setContentType("application/json;charset=utf-8");

            PrintWriter writer = response.getWriter();
            Result result = new Result(403,"权限不足",null);
            //把java对象转换为json字符串。---
            String jsonStr = JSONUtil.toJsonStr(result);
            writer.print(jsonStr);

            writer.flush();
            writer.close();
        });
    }
}